package com.sys.basics.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sys.basics.dao.SysRoleResourceLkDao;
import com.sys.basics.entity.SysRoleResourceLk;
import com.sys.basics.entity.vo.RoleResourceVo;
import com.sys.basics.utils.ArrayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.sys.basics.entity.SysRole;
import com.sys.basics.dao.SysRoleDao;
import com.sys.basics.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @author: ares
 * @date: 2021-10-08
 * @description: 角色表 服务实现类
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole> implements SysRoleService {
    @Autowired
    SysRoleDao sysRoleDao;

    @Autowired
    SysRoleResourceLkDao sysRoleResourceLkDao;

    @Override
    public List<SysRole> getListByUserAndOrg(Long userId, Long orgId) {
        return sysRoleDao.getListByUserAndOrg(userId, orgId);
    }

    @Override
    public IPage<SysRole> getPagesByOrg(Page<SysRole> page, Long orgId, SysRole roleParams) {
        return sysRoleDao.getPagesByOrg(page, orgId, roleParams);
    }

    @Override
    public SysRole getByOrgAndName(Long orgId, String roleName) {
        LambdaQueryWrapper<SysRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(SysRole::getOrgId, orgId).eq(SysRole::getRoleName, roleName);
        return sysRoleDao.selectOne(roleLambdaQueryWrapper);
    }

    @Override
    public int createRoleLinkResource(@Valid RoleResourceVo role) {
        List<Long> resourceIds = role.getResourceIds();
        SysRole sysRole = new SysRole();
        sysRole.setOrgId(role.getOrgId());
        sysRole.setRoleName(role.getRoleName());
        sysRole.setRoleSign(role.getRoleSign());
        sysRole.setRemark(role.getRemark());

        int insertCount = sysRoleDao.insert(sysRole);
        Long insertedRoleId = sysRole.getId();
        if (resourceIds.size() > 0) {
            sysRoleResourceLkDao.batchCreate(insertedRoleId, resourceIds);
        }
        return insertCount;
    }

    @Override
    public int updateRoleLinkResource(@Valid RoleResourceVo role) {
        List<Long> resourceIds = role.getResourceIds();
        Long roleId = role.getId();
        SysRole sysRole = new SysRole();
        sysRole.setId(roleId);
        sysRole.setRoleName(role.getRoleName());
        sysRole.setRoleSign(role.getRoleSign());
        sysRole.setRemark(role.getRemark());

        int updateCount = sysRoleDao.updateById(sysRole);

        HashMap<String, List<Long>> linkedResource = getLinkedResource(role);

        HashMap<String, Object> resourceCompareResult = ArrayUtils.arrayCompare(linkedResource.get("linkedResourceIds"), resourceIds);
        List<Long> missingLinkedResourceIds = (List<Long>) resourceCompareResult.get("missing");
        List<Long> excessLinkedResourceIds = (List<Long>) resourceCompareResult.get("excess");
        log.info("移除的资源ID: {}", missingLinkedResourceIds);
        log.info("增加的资源ID: {}", excessLinkedResourceIds);
        if (missingLinkedResourceIds.size() > 0) {
            sysRoleResourceLkDao.batchRemove(roleId, missingLinkedResourceIds);
        }
        if (excessLinkedResourceIds.size() > 0) {
            sysRoleResourceLkDao.batchCreate(roleId, excessLinkedResourceIds);
        }
        return updateCount;
    }

    @Override
    public boolean removeRoleAndLinkedResourceById(Long roleId) {
        sysRoleResourceLkDao.removeByRoleId(roleId);
        int deleteById = sysRoleDao.deleteById(roleId);
        return deleteById == 1;
    }

    /**
     * @author: ares
     * @date: 2021/11/11 20:49
     * @description: 获取角色关联的资源id
     * @param role
     * @return
     */
    private HashMap<String, List<Long>> getLinkedResource(SysRole role) {
        List<SysRoleResourceLk> roleLinkedResource = sysRoleResourceLkDao.getLinkedResourceByRoleId(role.getId());
        HashMap<String, List<Long>> hashMap = new HashMap<>();
        List<Long> linkedResourceIds = new ArrayList<>();

        for (SysRoleResourceLk sysRoleResourceLk : roleLinkedResource) {
            linkedResourceIds.add(sysRoleResourceLk.getResourceId());
        }

        hashMap.put("linkedResourceIds", linkedResourceIds);
        return hashMap;
    }
}
